const User = require('../model/user.model');
// 使用模糊查询需要先引入Op
const seq = require('sequelize');
const Op = seq.Op;

// 服务层 读写数据库
class UserService {
    // 添加用户
    async createUser(mobile, user_name, password, profile, time_ban) {
        // User.create({
        //     user_name: user_name,
        //     password: password
        // });
        // 属性和值一样可以简写
        let res = await User.create({mobile, user_name, password, profile, time_ban});
        return res;
    }

    async getUserInfo({id, mobile, user_name, password, is_admin, profile, time_ban}) {
        let whereObj = {};
        id && Object.assign(whereObj, {id});
        user_name && Object.assign(whereObj, {user_name});
        mobile && Object.assign(whereObj, {mobile});
        time_ban && Object.assign(whereObj, {time_ban});
        password && Object.assign(whereObj, {password});
        is_admin && Object.assign(whereObj, {is_admin});
        profile && Object.assign(whereObj, {profile});
        let res = await User.findOne({
            attributes: {exclude: []},
            where: whereObj
        });
        return res || '';
    }

    async getUserList({id, mobile, user_name, is_admin, time_ban, pageInfo}) {
        let whereObj = {};
        id && Object.assign(whereObj, {id});
        is_admin && Object.assign(whereObj, {is_admin});
        time_ban && Object.assign(whereObj, {time_ban});
        // 加入模糊查询
        user_name && Object.assign(whereObj, {
            user_name: {
                [Op.like]: `%${user_name}%`
            },
        });
        mobile && Object.assign(whereObj, {
            mobile: {
                [Op.like]: `%${mobile}%`
            },
        });

        // 查数量
        let count = await User.count({where: whereObj});
        let res;
        if (count !== 0) {
            let _pageInfo = {};
            if (pageInfo) {
                let {pageIndex, pageSize} = JSON.parse(pageInfo);
                _pageInfo = {
                    limit: pageSize,
                    offset: (pageIndex - 1) * pageSize
                }
            }
            res = await User.findAll({
                attributes: {exclude: ['password']},
                where: whereObj,
                ..._pageInfo
            });
        }
        return {list: res, count: count} || null;
    }

    async updateUserInfo({id, mobile, user_name, password, is_admin, profile, time_ban}) {
        let whereObj = {id};
        let newUser = {};
        user_name && Object.assign(newUser, {user_name});
        mobile && Object.assign(newUser, {mobile});
        time_ban && Object.assign(newUser, {time_ban});
        password && Object.assign(newUser, {password});
        is_admin && Object.assign(newUser, {is_admin});
        profile && Object.assign(newUser, {profile});
        let res = await User.update(newUser, {
            where: whereObj
        });
        return res[0] > 0;
    }
}

module.exports = new UserService();